import { Collection, Document } from 'mongodb';
import {
  prop_add_type_arr,
  req_info_add_type,
} from '../../Classes/cla_req_info_add_type';
import { check_cur_uni_type_info } from './Classes/cla_check_cur_uni_type_info';
import { get_db_cur_uni_type } from './Func/get_db_cur_uni_type';
import { update_cur_uni_type_count } from './Classes/cla_update_cur_uni_type_count';
import {
  prop_cur_uni_cur_type_count,
  sign_cur_uni_type_info,
} from './Classes/cla_sign_cur_uni_type_info';

let db_type_cur_uni: Collection<Document>;

/**
 * 添加 类型 及 更新 相应 添加 次数
 */
export function sign_cur_uni_type_add_type(cur_info: req_info_add_type) {
  db_type_cur_uni = get_db_cur_uni_type(cur_info);

  let cur_type_id: string;

  for (cur_type_id of cur_info[prop_add_type_arr]) {
    sign_cur_type_info(cur_info, cur_type_id);
  }
}

async function sign_cur_type_info(
  cur_info: req_info_add_type,
  cur_type_id: string
) {
  let check_cur_type_count = new check_cur_uni_type_info(cur_type_id);

  let cur_type_count = await db_type_cur_uni
    .find(check_cur_type_count)
    .toArray();

  if (cur_type_count.length == 1) {
    let update_info = new update_cur_uni_type_count(
      cur_type_count[0][prop_cur_uni_cur_type_count]
    );

    await db_type_cur_uni.updateOne(check_cur_type_count, update_info);

    return `更新 成功`;
  }

  let sign_cur_type = new sign_cur_uni_type_info(cur_info, cur_type_id);

  await db_type_cur_uni.insertOne(sign_cur_type);

  return `添加 成功`;
}
